<?php


namespace Transparency;

use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\RequestOptions;
use Transparency\Errors\AuthorizationException;

class Auth
{
    protected $client;

    protected $httpClient;

    protected $authHost;

    public function __construct(Client $client)
    {
        $this->client = $client;
        $this->httpClient = new GuzzleHttpClient();

        $this->authHost = 'https://tpncy-web-services.auth.us-east-1.amazoncognito.com';
    }

    public function getToken()
    {
        try{
            $response = $this->httpClient->post($this->authHost . '/oauth2/token', [
                RequestOptions::FORM_PARAMS => [
                    'client_id' => $this->client->getClientId(),
                    'client_secret' => $this->client->getClientSecret(),
                    'grant_type' => 'client_credentials',
                ],
            ]);
            if ($response->getStatusCode() === 200) {
                $data = $response?->getBody()?->getContents();
                return json_decode($data, true) ?? [];
            }
        }catch (RequestException $e){
            throw new AuthorizationException($e->getResponse()?->getBody()?->getContents());
        }
    }
}
